import axios from 'axios';
import { warnMsg } from './utils/messages';

const api = axios.create({
  baseURL: '/api',
  timeout: 5000
});

api.interceptors.response.use(
  (response) => {
    const { data } = response;
    if (!data.success) {
      warnMsg(data.message);
    }
    return response;
  }
);

function createRequestWithPrefix(prefix) {
  return function requestWithPrefix(method, url, dataOrParams = {}, config = {}) {
    const fullUrl = `/${prefix}${url}`;
    return api({
      method,
      url: fullUrl,
      ...(method === 'get' || method === 'delete'
        ? { params: dataOrParams }
        : { data: dataOrParams }),
      ...config,
    });
  };
}

export { createRequestWithPrefix };
